<?php

namespace Action\Widget\Box;

class Contacts extends \Library\Action\UserAction
	implements \Library\Action\AjaxAction {
	
	private $_user;
	private $_requests;
	private $_contacts;
	private $_moreRequests = false;
	private $_moreContacts = false;
	
	public function execute() {
		parent::execute();
		
		$user_id = (int) $this->getParam( 'id' );
		$this->_user = \Bean\User::get( $user_id );
		
		return array(
			'content' => $this->view(),
			'all' => count($this->getContacts()) > 0
		);
	}

	public function getUser() {
		return $this->_user;
	}
	
	public function getRequests() {
		if( $this->_requests === null ) {
			$requests = _q()->getE( 'users_requests', array(
				'acceptor_id' => $this->getUser()->getUserId(),
				'accepted' => 0
			), 'RAND()', 0, 4 );
			if( count($requests) > 3 ) {
				$this->_moreRequests = true;
				$requests = array_slice( $requests, -3, 3 );
			}
			$this->_requests = array();
			foreach( $requests as $request ) {
				$request = new \Bean\User\Request( $request );
				$this->_requests[] = new Contacts\Request( $request );
			}
		}
		return $this->_requests;
	}
	
	public function hasMoreRequests() {
		return $this->_moreRequests;
	}
	
	public function getContacts() {
		if( $this->_contacts === null ) {
			$contacts = _q()->getE( 'users_contacts', array(
				'user_id' => $this->getUser()->getUserId()
			), 'RAND()', 0, 7 );
			if( count($contacts) > 6 ) {
				$this->_moreContacts = true;
				$contacts = array_slice( $contacts, -3, 3 );
			}
			$this->_contacts = array();
			foreach( $contacts as $contact ) {
				$this->_contacts[] = new \Library\Widget\Box\Contacts\User( \Bean\User::get( $contact['contact_id'] ) );
			}
		}
		return $this->_contacts;
	}
	
	public function hasMoreContacts() {
		return $this->_moreContacts;
	}
}
